/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable react-hooks/exhaustive-deps */
/*
 * @Author: 周海 zhouhaib@yonyou.com
 * @Date: 2022-12-17 11:32:53
 * @LastEditors: zhouhai zhouhaib@yonyou.com
 * @LastEditTime: 2025-04-10 15:12:51
 */
/* eslint-disable jsx-a11y/anchor-is-valid */
import {
    changeJobStatus,
    delSysjob,
    listSysjob,
    runJob,
} from '@/api/monitor/sysjob';
import PageDiv from '@/components/PageDiv';
import ResizeTable from '@/components/ResizeTable';
import { useStore } from '@/store';
import { pageInfo } from '@/type.d/ajaxResult';
import { SysJobDomain } from '@/type.d/monitor/sysjob';
import {
    ActionType,
    ProColumns,
    ProFormInstance,
    ProFormRadio,
    ProFormSelect,
    ProFormText,
    QueryFilter,
    TableDropdown,
} from '@ant-design/pro-components';
import { Button, message, Modal, Popconfirm, Space, Switch } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import SysJobCard from './sysjobCard';

import { ExclamationCircleOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
// import './index.less';

const Sysjob: React.FC = () => {
    const { layoutStore } = useStore();
    const navigate = useNavigate()
    const actionRef = useRef<ActionType>();
    const queryformRef = useRef<ProFormInstance<SysJobDomain>>();
    const [queryValue, setQueryValue] = useState<SysJobDomain>({});
    const [tableListDataSource, setTableListDataSource] = useState<SysJobDomain[]>([]);

    const [sysJobStatusOptions, setSysJobStatusOptions] = useState<any[]>([]);
    const [sysJobGroupOptions, setSysJobGroupOptions] = useState<any[]>([]);

    const [pageInfo, setPageInfo] = useState<pageInfo>({
        current: 1,
        pageSize: 10,
        total: 0
    });

    const [cardData, setCardData] = useState<SysJobDomain>({});
    const [pageStatus, setPageStatus] = useState<'List' | 'Card'>('List');
    const [isedit, setIsedit] = useState<boolean>(false);


    const newdata = {}

    /**
     * 列表字段配置
     */
    const columns: ProColumns<SysJobDomain>[] = [
        {
            title: '任务编号',
            dataIndex: 'jobId',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '任务名称',
            dataIndex: 'jobName',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '任务组名',
            dataIndex: 'jobGroup',
            valueType: 'select',
            align: 'left',
            width: '50',
            fieldProps: {
                options: sysJobGroupOptions
            },
        },
        {
            title: '调用目标字符串',
            dataIndex: 'invokeTarget',
            ellipsis: true
        },
        {
            title: 'cron执行表达式',
            dataIndex: 'cronExpression',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '计划执行错误策略',
            dataIndex: 'misfirePolicy',
            valueType: 'text',
            align: 'left',
            width: '50',
            hideInTable: true
        },
        {
            title: '是否并发执行',
            dataIndex: 'concurrent',
            valueType: 'text',
            align: 'left',
            width: '50',
            hideInTable: true
        },
        {
            title: '状态',
            dataIndex: 'status',
            valueType: 'radio',
            align: 'left',
            width: '50',
            fieldProps: {
                options: sysJobStatusOptions
            },
            render: (dom: React.ReactNode, entity: SysJobDomain) => {
                let text = entity.status === "0" ? "停用" : "启用";
                return (
                    <Popconfirm
                        title={'确认要"' + text + '""' + entity.jobName + '"任务吗？'}
                        onConfirm={() => handleStatusChange(entity)}>
                        <Switch checked={entity.status === '0'} />
                    </Popconfirm>
                )

            }
        },
        {
            title: '备注信息',
            dataIndex: 'remark',
            hideInTable: true
        },
        {
            title: '操作',
            width: 180,
            key: 'option',
            valueType: 'option',
            render: (_dom: React.ReactNode, entity: SysJobDomain) => [
                <a key="view" onClick={() => {
                    onView(entity)
                }}>详情</a>,
                <a key="edit" onClick={() => {
                    toCard(entity, true);
                }}>修改</a>,
                <Popconfirm title="确定要删除数据吗？" okText="是" cancelText="否" onConfirm={() => {
                    onDelete(entity)
                }}>
                    <a key="delete">删除</a>
                </Popconfirm>,
                <TableDropdown
                    key="actionGroup"
                    menus={[
                        { key: 'run', name: '执行一次' },
                        { key: 'joblog', name: '调度日志' },
                    ]}
                    onSelect={
                        (key: string) => {
                            if("run" === key){
                                handleRun(entity);
                            }else if("joblog" === key){
                                navigate(`/monitor/jobLog/${entity.jobName}`,{
                                    state:{
                                        showname: `${entity.jobName}日志`
                                    }
                                });
                            }
                        }
                    }
                />,


            ],
        },
    ];

    const handleRun = (entity: SysJobDomain) => {
        Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined />,
            content: '确认要立即执行一次"' + entity.jobName + '"任务吗？',
            onOk:()=>{
                if(entity.jobId && entity.jobGroup){
                    layoutStore.OpenSpanning()
                    runJob(entity.jobId, entity.jobGroup).then(()=>{
                        message.success('执行成功！');
                    }).finally(() => layoutStore.CloseSpanning())
                }
                
            }
          });
    } 


    const handleStatusChange = (entity: SysJobDomain) => {
        if (entity.jobId && entity.status) {
            layoutStore.OpenSpanning()
            changeJobStatus(entity.jobId, entity.status === "0" ? "1" : "0").then((res) => {
                setTableListDataSource(tableListDataSource.map((item) => {
                    if (item.jobId === res.data.jobId) {
                        return res.data
                    } else {
                        return item
                    }
                }))
            }).finally(() => layoutStore.CloseSpanning())
        }

    }

    const toCard = (data: SysJobDomain, isEdit: boolean = false) => {
        setQueryValue(queryformRef.current?.getFieldsValue() || {})
        setPageStatus('Card')
        setCardData({ ...data })
        setIsedit(isEdit)
    }

    const onView = (data: SysJobDomain) => {
        toCard(data)
    }


    const onDelete = (dedata: SysJobDomain) => {
        if (dedata.jobId) {
            layoutStore.OpenSpanning()
            delSysjob(dedata.jobId).then(() => {
                setTableListDataSource(tableListDataSource.filter((item) => {
                    return item.jobId !== dedata.jobId
                }))
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        }

    }


    const headButton = () => {
        return <Space>
            <Button
                size='small'
                key="add"
                type="primary"
                onClick={() => toCard(newdata, true)}
            >
                新增
            </Button>
        </Space>
    }

    //监听分页得操作
    useEffect(() => {
        if (pageInfo.total > 0) {
            //如果原页面有数据，触发查询
            const _data = queryformRef?.current?.getFieldsValue()
            onQuery({...pageInfo,..._data})
        }
    }, [pageInfo.current,pageInfo.pageSize])


    const onQuery = async (_data: any) => {
        if (_data.createTime) {
            _data.params = {}
            _data.params['beginTime'] = _data.createTime[0];
            _data.params['endTime'] = _data.createTime[1];
            delete _data.createTime
        }

        layoutStore.OpenSpanning();
        listSysjob(_data).then((res) => {
            setTableListDataSource(res.data)
            if (res.total) {
                setPageInfo({ ...pageInfo, total: res.total })
            }

        }).finally(() => {
            layoutStore.CloseSpanning()
        })

        return _data;
    }

    const onPageChange: (current: number, pageSize: number) => void = (current, pageSize) => {
        setPageInfo({ ...pageInfo, current, pageSize });
    };

    useEffect(() => {
        if (pageStatus === 'List') {
            queryformRef.current?.setFieldsValue(queryValue)
        }
    }, [pageStatus])


    return (
        <PageDiv>{
            pageStatus === 'List' ? <PageDiv>
                <QueryFilter<SysJobDomain>
                    defaultCollapsed
                    split
                    span={4}
                    onFinish={(_data) => onQuery({ ...pageInfo, ..._data, current: 1, })}
                    formRef={queryformRef}>
                    <ProFormText key='jobName' name="jobName" label="任务名称" />

                    <ProFormSelect key='jobGroup' name="jobGroup"
                        label="任务组名"
                        options={sysJobGroupOptions}
                    />

                    <ProFormRadio.Group key='status' name="status"
                        label="状态"
                        options={sysJobStatusOptions}
                    />

                </QueryFilter>
                <ResizeTable<SysJobDomain>
                    rowKey={'jobId'}
                    onRow={record => {
                        return {
                            onDoubleClick: event => {
                                onView(record)
                            },
                        };
                    }}
                    dataSource={tableListDataSource}
                    actionRef={actionRef}
                    columns={columns}
                    cardBordered
                    revalidateOnFocus={false}
                    pagination={{
                        ...pageInfo,
                        showTitle: false,
                        onChange: onPageChange
                    }}
                    headerTitle={headButton()}
                >
                </ResizeTable>
            </PageDiv> :
                <SysJobCard
                    onBack={() => setPageStatus('List')}
                    isedit={isedit}
                    setIsedit={setIsedit}
                    sysJobStatusOptions={sysJobStatusOptions}
                    sysJobGroupOptions={sysJobGroupOptions}
                    cardData={cardData}
                    newdata={newdata}
                    tableListDataSource={tableListDataSource}
                    setTableListDataSource={setTableListDataSource} />}
        </PageDiv>

    )
}
export default Sysjob;